package com.wdl.modules.myhouse.controller;


import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamResolution;
import com.wdl.modules.myhouse.config.ImageUtil;
import com.wdl.modules.myhouse.dto.VideoDto;
import com.wdl.modules.myhouse.entity.TempEntity;
import com.wdl.modules.myhouse.entity.VideoEntity;
import com.wdl.modules.myhouse.service.VideosService;
import com.wdl.modules.myhouse.common.Code;
import com.wdl.modules.myhouse.common.Constant;
import com.wdl.modules.myhouse.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 昏昏的君
 */
@RestController
@RequestMapping("/video")
@Slf4j
@Api(tags = "视频接口")
public class VideoController {


    @Autowired
    private ThreadPoolExecutor threadPool;
    @Autowired
    private VideosService videosService;


    @PostMapping("/upload")
    @ApiOperation(value = "视频上传接口", tags = "视频上传接口")
    public Result<List<String>> upload(@RequestParam("file") MultipartFile[] files) {

        try {
            List<String> list = new ArrayList();
            for (MultipartFile file : files) {
                String filename = file.getOriginalFilename();
                String suffix = file.getOriginalFilename().substring(filename.lastIndexOf("."));
                String newName = UUID.randomUUID().toString().replaceAll("-", "");
                String fileUrl = Constant.VIDEO_STORAGE_ADDR + newName + suffix;
                file.transferTo(Paths.get(fileUrl));
                list.add(newName.concat(suffix));
            }
            return new Result<List<String>>().ok(list);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result<List<String>>().error(Code.INTERNAL_ERROR.getCode(), Code.INTERNAL_ERROR.getMessage());
        }


    }

    @PostMapping("/save")
    public Result save( @RequestBody  VideoDto videoDto) {
        try {
            VideoEntity entity = new VideoEntity();
            BeanUtils.copyProperties(videoDto, entity);
            List<String> videos = videoDto.getVideo();
            StringBuilder builder = new StringBuilder();
            if (videos != null) {
                for (int i = 0; i < videos.size(); i++) {
                    if (i != videos.size() - 1) {
                        builder.append(Constant.VIDEO_STORAGE_ADDR + videos.get(i) + ",");
                    } else {
                        builder.append(Constant.VIDEO_STORAGE_ADDR + videos.get(i));
                    }
                }
            }
            entity.setVideoUrl(builder.toString());
            videosService.save(entity);
        } catch (BeansException e) {
            e.printStackTrace();
            return new Result().error();
        }
        return new Result().ok();
    }


    @GetMapping("/video")
    public String getImage(HttpServletResponse response) {
        Webcam webcam = null;
        try {
            webcam = Webcam.getDefault();
            webcam.setViewSize(WebcamResolution.VGA.getSize());
            webcam.open();
            BufferedImage image = webcam.getImage();
            long time = System.currentTimeMillis();
            String baseUrl = "I:\\新建文件夹 (6)\\temp\\";
//            String fileUrl = "E:\\VSCode\\my-house\\static\\temp\\" + time + ".png";
            String fileUrl = baseUrl + time + ".png";
            threadPool.execute(() -> {
                try {
                    FileOutputStream out = new FileOutputStream(fileUrl);
                    ImageIO.write(image, "PNG", out);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            return "如果没有反应,请刷新一下";
        } finally {
            webcam.close();
        }
    }


    @PostMapping("/hello")
    public String getImage1(@RequestBody TempEntity tempEntity, HttpServletRequest request) {
        log.info("数据{}",tempEntity);
        String base64File = tempEntity.getData();
        log.info("数据长度:{}",base64File.length());
        log.info("拿到的base64文件:{}", base64File);
        String path = "I:\\新建文件夹 (6)\\temp\\";
        String s = ImageUtil.generateImage(base64File, path, request);
        log.info("文件相对路径:{}", s);
        return "<h2>您访问的网页有点慢</h2>";
    }
//
//    @PostMapping("/hello")
//    public String getImage1(@RequestBody TempEntity tempEntity, HttpServletRequest request) {
//        String base64File = tempEntity.getData();
//        log.info("拿到的base64文件:{}", base64File);
//        String path = "I:\\新建文件夹 (6)\\temp\\";
////        String s = ImageUtil.generateImage(base64File, path, request);
////        log.info("文件相对路径:{}", s);
//        return "<h2>您访问的网页有点慢</h2>";
//    }


}
